import { _decorator, Button, Component, EditBox, Node, Sprite, SpriteFrame, Vec2, tween, Animation, AnimationClip, Prefab, instantiate, log, Input, input, EventKeyboard, KeyCode } from 'cc';
import { UIComponent } from '../platform/ui/UIComponent';
import { bind, bindValue } from '../platform/ui/UIDecorator';
import { Player } from './Player';
import { NetworkManager } from './NetManager';
import { GlobalEventMgr } from '../platform/event/GlobalEventMgr';
import { SyncDemoEvent } from './SyncDemoEvent';
import { MsgTypes } from './MsgTypes';
import { GameState } from './GameState';
import { LogMgr } from '../platform/log/LogMgr';
import { Msg_Login_Req, Msg_Login_Resp } from './msgs';
const { ccclass, property } = _decorator;

@ccclass('SyncDemo')
export class SyncDemo extends UIComponent {

    //#region UI绑定

    @bind(Node)
    private login: Node;

    @bindValue(EditBox)
    private uid: string = '';

    @bind(Node)
    private login_submit: Node;
    //#endregion


    @bind(Node,"scene")
    private scene: Node = null;

    @property(Prefab)
    private playerPrefab:Prefab

    private localPlayer: Player = null;
    private remotePlayers: Map<string, Player> = new Map();
    private networkManager: NetworkManager = null;
    

    protected start(): void {
        this.login_submit.on(Button.EventType.CLICK, this.onLoginSubmit, this);
        GlobalEventMgr.ins.addNotice(SyncDemoEvent.LoginSuccess,this,this.onLoginSuccess);
        GlobalEventMgr.ins.addNotice(SyncDemoEvent.PlayerStateUpdate,this,this.onPlayerStateUpdate);
    }

    onLoginSubmit() {
        if(this.uid == '' || this.uid == null) return;

        this.networkManager = NetworkManager.getInstance();
        this.networkManager.connect(()=>{
            this.networkManager.sendMessage(MsgTypes.Login,new Msg_Login_Req(this.uid));
        },()=>{
            this.login.active = true;
            LogMgr.err("连接失败");
        }); 
    }

    
    onLoginSuccess(data:Msg_Login_Resp){
        let {uid,x,y} = data;
        let playerNode = instantiate(this.playerPrefab);
        this.scene.addChild(playerNode);
        
        this.localPlayer = playerNode.getComponent(Player);
        this.localPlayer.init(uid,x,y,true);
    }

    onPlayerStateUpdate(data:GameState[]){
        data.forEach(state => {
            if(state.playerId != this.localPlayer.uid){
                GlobalEventMgr.ins.emit(SyncDemoEvent.RemotePlayerStateUpdate, state);
            }
        })
    }
}


